package com.bnzj.core.util;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.extern.slf4j.Slf4j;

/**
 * @author barry
 * @date 2019-10-12
 */
@Slf4j
public class JsonUtils {
    
    private static volatile ObjectMapper objectMapper;

    public static ObjectMapper getObjectMapper() {
        if(objectMapper == null) {
            synchronized (JsonUtils.class) {
                if(objectMapper == null) {
                    objectMapper = SpringUtils.get(ObjectMapper.class);
                }
            }
        }
        return objectMapper;
    }
    
    public static ArrayNode createArrayNode() {
        return getObjectMapper().createArrayNode();
    }
    
    public static ObjectNode createObjectNode() {
        return getObjectMapper().createObjectNode();
    }
    
    public static ObjectNode valueToObjectNode(String str) {
        return (ObjectNode)valueToTree(str);
    }
    
    public static ArrayNode valueToArrayNode(String str) {
        return (ArrayNode)valueToTree(str);
    }
    
    public static JsonNode valueToTree(String str) {
        ObjectMapper mapper = getObjectMapper();
        try {
            return mapper.readTree(str);
        } catch (Exception e) {
            log.error("该json字符串[" + str + "]无法转换成对象");
            log.info("", e);
        }
        return null;
    }
    
    public static JsonNode valueToTree(Object object) {
        ObjectMapper mapper = getObjectMapper();
        return mapper.valueToTree(object);
    }
    
    public static String objToJson(Object object) {
        ObjectMapper mapper = getObjectMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            log.error("该对象无法转换成json字符串");
            log.info("", e);
        }
        return "";
    }

    public static <T> T jsonToObject(String str, Class<T> cls) {
        ObjectMapper mapper = getObjectMapper();
        try {
            return mapper.readValue(str, cls);
        } catch (Exception e) {
            log.error("该json字符串[" + str + "]无法转换成对象");
            log.info("", e);
        }
        return null;
    }

    public static <T extends Object> List<T> jsonToObject(String str, TypeReference<List<T>> typeReference) {
        ObjectMapper mapper = getObjectMapper();
        try {
            return mapper.readValue(str, typeReference);
        } catch (Exception e) {
            log.error("该json字符串[" + str + "]无法转换成对象");
            log.info("", e);
        }
        return null;
    }
}
